package com.suning.sawp.in.controller.model;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.ExportConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.OrgInfo;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.exception.SawpException;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.model.ModelAnalyseInService;
import com.suning.sawp.intf.model.ModelErrorConstant;
import com.suning.sawp.intf.model.vo.ModelRecommendBaseVo;
import com.suning.sawp.service.impl.model.ModelAnalyseInServiceImpl;
import com.suning.sawp.service.util.CsvUtils;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.ExportFileUtil;
import com.suning.sawp.vo.csv.ExportCsvFileVo;
import com.suning.sawp.vo.model.ModelContributionAreaExResponse;
import com.suning.sawp.vo.model.ModelContributionAreaResponse;
import com.suning.sawp.vo.model.ModelContributionResponse;
import com.suning.sawp.vo.model.ModelSaleTopResponse;
import com.suning.sawp.vo.model.ModelValidAreaResponse;
import com.suning.sawp.vo.model.ModelValidInAreaResponse;
import com.suning.sawp.vo.model.ModelValidResponse;

/**
 * 样机分析
 * 
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@RequestMapping("/adminPage/model")
@Controller
public class ModelAnalyseInController extends DjBaseController {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ModelAnalyseInController.class);

    /**
     * 样机分析服务
     */
    @Autowired
    ModelAnalyseInService modelService;
    
    /**
     * 应用服务器上的临时文件存放目录
     */
    @Value("#{settingConfig['fs_url']}")
    private String fsUrl;
    
    @Resource
    ExportFileUtil exportFileUtil;
    
    /**
     * 查询全国样机有效率
     * 
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelValid.do")
    public MyGsonView queryModelValid(String cateCode) {
        LOGGER.info("queryModelValid enter, cateCode={}", cateCode);
        ReturnMsg<ModelValidResponse> ret = new ReturnMsg<ModelValidResponse>();
        try {
            String region5Code = null;
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            if (OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())
                    || OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                    region5Code = employeeInfo.getRegion5Code();
                }
                // 调用服务查询
                ModelValidResponse resp = modelService.queryModelValid(region5Code, cateCode);
                LOGGER.debug("queryModelValid response={}", resp);
                ret.setData(resp);
            } else {
                ret.setError(ErrorCodeConstants.ERR_0035);
            }
            
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryModelValid error", e);
        }
        LOGGER.info("queryModelValid exit, cateCode={}", cateCode);
        return setGsonView(ret);
    }

    /**
     * 查询大区or分公司样机有效率
     * 
     * @param disCode
     * @param pageSize
     * @param currIndex
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
//    @RequestMapping("/queryModelValidArea.do")
    @Deprecated
    public MyGsonView queryModelValidArea(@RequestParam(value="disCode", required=false)String disCode, Integer pageSize, Integer pageNo) {
        LOGGER.info("queryModelValidArea enter, disCode={},pageSize={},pageNo={}", new Object[] { disCode, pageSize,
                pageNo });
        ReturnMsg<ModelValidInAreaResponse> ret = new ReturnMsg<ModelValidInAreaResponse>();
        try {
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            
            String region5Code = null;
            // 总部、大区角色可以查看
            if (OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())
                    || OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
                    region5Code = employeeInfo.getRegion5Code();
                }
                // 调用服务查询
                ModelValidInAreaResponse resp = modelService.queryModelValidArea(disCode, region5Code,
                        DJStringUtils.initCurrIndex(pageNo, pageSize), DJStringUtils.initPageSize(pageSize));
                LOGGER.debug("queryModelValidArea response={}", resp);
                ret.setData(resp);
            } else {
                ret.setError(ErrorCodeConstants.ERR_0035);
            }
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryModelValidArea error", e);
        }
        LOGGER.info("queryModelValidArea exit, disCode={},pageSize={},pageNo={}", new Object[] { disCode, pageSize,
                pageNo });
        return setGsonView(ret);
    }
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉 前台在点击链接查看下一级页面时，才会有disCode、regionCode；其他情况后台通过登录人信息获取<br>
     * 如果disCode、regionCode都为空，根据登陆用户组织级别来判断展示什么数据， <br>
     * ①若是全国账号，默认展示大区信息；若是大区账号，默认展示分公司信息；若是分公司账号，默认展示门店信息。<br>
     * ②如果disCode、regionCode不为空，根据编码来进行查询。
     *
     * @param disCode
     * @param regionCode
     * @param storeType
     * @param saleMonth 必填
     * @param pageSize
     * @param pageNo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelValidArea.do")
    public MyGsonView queryModelValidAreaEx(String disCode, String branchCode, String storeType, String saleMonth,
            Integer pageSize, Integer pageNo) { 
        LOGGER.info("queryModelValidArea enter, disCode={},pageSize={},pageNo={}", new Object[] { disCode, pageSize,
                pageNo });
        ReturnMsg<ModelValidAreaResponse> ret = new ReturnMsg<ModelValidAreaResponse>();
        try {
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            if (StringUtils.isBlank(saleMonth)) {
                ret.setError(ErrorCodeConstants.ERR_0001);
            }
            // 总部、大区、分公司角色可以查看
            else if (OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())
                    || OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())
                    || OrgInfo.ORG_LEVEL.COMPANY_LEVEL.equals(employeeInfo.getOrgLevel())) {
                // 所属大区编码
                String belongsDisCode = employeeInfo.getRegion5Code();
                // 所属分公司编码
                String belongsBranchCode = employeeInfo.getBranchCode();
                if (null == pageSize) {
                    pageSize = 10;
                }
                if (null == pageNo) {
                    pageNo = 1;
                }
                // 查询
                ModelValidAreaResponse resp = modelService.queryModelValidAreaEx(employeeInfo.getOrgLevel(), disCode,
                        branchCode, belongsDisCode, belongsBranchCode, storeType, saleMonth, pageNo, pageSize);
                LOGGER.debug("queryModelValidArea response={}", resp);
                ret.setData(resp);
            } else {
                ret.setError(ErrorCodeConstants.ERR_0035);
            }
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryModelValidArea error", e);
        }
        LOGGER.info("queryModelValidArea exit, disCode={},pageSize={},pageNo={}", new Object[] { disCode, pageSize,
                pageNo });
        return setGsonView(ret);
    }

    /**
     * 查询全国样机贡献率
     * 
     * @param saleMonth
     * @param storeType 1门店 2服务站
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelContribution.do")
    public MyGsonView queryModelContribution(String saleMonth, String storeType) {
        LOGGER.info("queryModelContribution enter, saleMonth={}", saleMonth);
        ReturnMsg<ModelContributionResponse> ret = new ReturnMsg<ModelContributionResponse>();
        if (StringUtils.isBlank(saleMonth)) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, "入参saleMonth必填");
        } else {
            try {
                EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
                // 调用服务查询
                ModelContributionResponse resp = modelService.queryModelContribution(employeeInfo, saleMonth, storeType);
                LOGGER.debug("queryModelContribution response={}", resp);
                ret.setData(resp);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error("queryModelContribution error", e);
            }
        }
        LOGGER.info("queryModelContribution exit, saleMonth={}", saleMonth);
        return setGsonView(ret);
    }

    /**
     * 查询大区or分公司贡献率
     * 
     * @param disCode
     * @param pageSize
     * @param currIndex
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
//    @RequestMapping("/queryModelContributionArea.do")
    @Deprecated
    public MyGsonView queryModelContributionArea(String disCode, Integer pageSize, Integer pageNo) {
        LOGGER.info("queryModelContributionArea enter, disCode={},pageSize={},pageNo={}", new Object[] { disCode,
                pageSize, pageNo });
        ReturnMsg<ModelContributionAreaResponse> ret = new ReturnMsg<ModelContributionAreaResponse>();
        try {
            String belongRegion5Code = null;
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            if (!OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())) {
                // 非总部按大区来
                belongRegion5Code = employeeInfo.getRegion5Code();
            }
            // 调用服务查询
            ModelContributionAreaResponse resp = modelService.queryModelContributionArea(belongRegion5Code, disCode,
                    DJStringUtils.initCurrIndex(pageNo, pageSize), DJStringUtils.initPageSize(pageSize));
            LOGGER.debug("queryModelContributionArea response={}", resp);
            ret.setData(resp);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryModelContributionArea error", e);
        }
        LOGGER.info("queryModelContributionArea exit, disCode={},pageSize={},pageNo={}", new Object[] { disCode,
                pageSize, pageNo });
        return setGsonView(ret);
    }
    
    /**
     * 
     * 功能描述: 查询大区or分公司or门店贡献率<br>
     * 〈功能详细描述〉前台在点击链接查看下一级页面时，才会有disCode、regionCode；其他情况后台通过登录人信息获取
     * 如果disCode、regionCode都为空，根据登陆用户组织级别来判断展示什么数据， <br>
     * ①若是全国账号，默认展示大区信息；若是大区账号，默认展示分公司信息；若是分公司账号，默认展示门店信息。<br>
     * ②如果disCode、regionCode不为空，根据编码来进行查询。
     *
     * @param disCode 大区
     * @param regionCode 分公司
     * @param storeType 1门店  2服务站
     * @param saleMonth 销售月份 
     * @param pageSize
     * @param pageNo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelContributionArea.do")
    public MyGsonView queryModelContributionAreaEx(String disCode, String branchCode, String storeType,
            String saleMonth, Integer pageSize, Integer pageNo) {
        LOGGER.info(
                "queryModelContributionAreaEx enter, disCode={},pageSize={},pageNo={},brandCode:{},storeType:{},saleMonth:{}",
                new Object[] { disCode, pageSize, pageNo, branchCode, storeType, saleMonth });
        ReturnMsg<ModelContributionAreaExResponse> ret = new ReturnMsg<ModelContributionAreaExResponse>();
        try {
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            if (StringUtils.isBlank(saleMonth)) {
                ret.setError(ErrorCodeConstants.ERR_0001);
            }
            // 总部、大区、分公司角色可以查看
            else if (OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())
                    || OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())
                    || OrgInfo.ORG_LEVEL.COMPANY_LEVEL.equals(employeeInfo.getOrgLevel())) {
                // 所属大区编码
                String belongsDisCode = employeeInfo.getRegion5Code();
                // 所属分公司编码
                String belongsBranchCode = employeeInfo.getBranchCode();
                if (null == pageSize) {
                    pageSize = 10;
                }
                if (null == pageNo) {
                    pageNo = 1;
                }
                // 调用服务查询
                ModelContributionAreaExResponse resp = modelService.queryModelContributionAreaEx(
                        employeeInfo.getOrgLevel(), disCode, branchCode, belongsDisCode, belongsBranchCode, storeType,
                        saleMonth, pageNo, pageSize);
                LOGGER.debug("queryModelContributionArea response={}", resp);
                ret.setData(resp);
            } else {
                ret.setError(ErrorCodeConstants.ERR_0035);
            }
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryModelContributionArea error", e);
        }
        LOGGER.info("queryModelContributionArea exit, disCode={},pageSize={},pageNo={}", new Object[] { disCode,
                pageSize, pageNo });
        return setGsonView(ret);
    }

    /**
     * 查询样机销售排行
     * 
     * @param pageSize
     * @param currIndex
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelContributionTop.do")
    public MyGsonView queryModelContributionTop(Integer pageSize, Integer pageNo) {
        LOGGER.info("queryModelContributionTop enter, pageSize={},pageNo={}", pageSize, pageNo);
        ReturnMsg<ModelSaleTopResponse> ret = new ReturnMsg<ModelSaleTopResponse>();
        try {
            // 调用服务查询
            ModelSaleTopResponse resp = modelService.queryModelContributionTop(
                    DJStringUtils.initCurrIndex(pageNo, pageSize), DJStringUtils.initPageSize(pageSize));
            LOGGER.debug("queryModelContributionTop response={}", resp);
            ret.setData(resp);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryModelContributionTop error", e);
        }
        LOGGER.info("queryModelContributionTop exit, pageSize={},pageNo={}", pageSize, pageNo);
        return setGsonView(ret);
    }

    /**
     * 下载大区or分公司12个月有效率数据
     * 
     * @param disCode
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
//    @RequestMapping("/downModelValidArea.do")
    @Deprecated
    public void downModelValidArea(String disCode, HttpServletResponse response) {
        LOGGER.info("downModelValidArea enter, disCode={}", disCode);
        try {
            // 调用服务查询
            String fileName = "";
            if (StringUtils.isNotBlank(disCode)) {
                // 查询大区信息
                fileName = disCode + "-fengongsiyouxiaolvfenxi-"
                        + DateUtils.getNextDayStr(0, DateUtils.YYYYMMDD_PATTERN);
            } else {
                fileName = "daquyangjiyouxiaoxingfenxi-" + DateUtils.getNextDayStr(0, DateUtils.YYYYMMDD_PATTERN);
            }
            // 非总部人员所归属的大区编码
            EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
            String belongDisCode = null;
            if (!OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(employeeInfo.getOrgLevel())) {
                belongDisCode = employeeInfo.getRegion5Code();
            }
            ExportCsvFileVo data = modelService.queryModelValidArea(disCode, belongDisCode);
            // 下载数据
            CsvUtils.exportFile(response, fileName, data.getData(), data.getHeader());
        } catch (Exception e) {
            LOGGER.error("downModelValidArea error", e);
        }
        LOGGER.info("downModelValidArea exit, disCode={}", disCode);
    }
    
    /**
     * 
     * 功能描述: 样机有效性分析数据下载<br>
     * 〈功能详细描述〉
     *
     * @param disCode
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    //FIXME 需验证
    @RequestMapping("/downModelValidArea.do")
    public void downModelValidAreaEx(String disCode, String branchCode, String storeType, String saleMonth,
            @RequestParam(defaultValue = "1", required = false) Integer index, HttpServletResponse response) {
        LOGGER.info("downModelValidAreaEx.disCode:{}, branchCode:{}, storeType:{}, saleMonth:{}, index:{}", disCode,
                branchCode, storeType, saleMonth, index);
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(saleMonth)) {
                LOGGER.error("downModelValidAreaEx.saleMonth:{}", saleMonth);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E001).getBytes());
                return;
            } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                LOGGER.error("downModelValidAreaEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E002).getBytes());
                return;
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelAnalyseInService.class.getName();
                String methodName = ExportConstants.ExportMethodName.EXPORT_MODEL_VALID_EX;
                
                String orgLevel = employeeInfo.getOrgLevel();
                String belongsDisCode = employeeInfo.getRegion5Code();
                String belongsBranchCode = employeeInfo.getBranchCode();
                
                @SuppressWarnings("unchecked")
                List<Object> params = new ArrayList<Object>(Arrays.asList(staffId, orgLevel, disCode,
                        branchCode, belongsDisCode, belongsBranchCode, storeType, saleMonth, index));
                exportFileUtil.saveExportTask(staffId, className, methodName, params);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (Exception e) {
            LOGGER.error("downModelValidAreaEx failed.", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        } finally {
            try {
                if (null != ouputStream) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("downModelValidAreaEx finally failed.", e);
            }
        }
    
    }
    
    /**
     * 
     * 下载大区or分公司12个月贡献率数据
     * 
     * @param disCode
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
//    @RequestMapping("/downModelContributionArea.do")
    @Deprecated
    public void downModelContributionArea(String disCode, HttpServletResponse response) {
        LOGGER.info("downModelContributionArea enter, disCode={}", disCode);
        try {
            // 调用服务查询
            String fileName = "";
            if (StringUtils.isNotBlank(disCode)) {
                // 查询大区信息
                fileName = disCode + "-fengongsigongxianlvfenxi-"
                        + DateUtils.getNextDayStr(0, DateUtils.YYYYMMDD_PATTERN);
            } else {
                fileName = "daquyangjigongxianlvfenxi-" + DateUtils.getNextDayStr(0, DateUtils.YYYYMMDD_PATTERN);
            }
            ExportCsvFileVo data = modelService.queryModelContributionArea(disCode);
            // 下载数据
            CsvUtils.exportFile(response, fileName, data.getData(), data.getHeader());
        } catch (Exception e) {
            LOGGER.error("downModelContributionArea error", e);
        }
        LOGGER.info("downModelContributionArea exit, disCode={}", disCode);
    }
    
    /**
     * 
     * 下载大区or分公司12个月贡献率数据
     * 
     * @param disCode
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/downModelContributionArea.do")
    public void downModelContributionAreaEx(String disCode, String branchCode, String storeType, String saleMonth,
            @RequestParam(defaultValue = "1", required = false) Integer index, HttpServletResponse response) {
        LOGGER.info("downModelContributionAreaEx enter, disCode={},branchCode:{},storeType:{},saleMonth:{},index:{}",
                disCode, branchCode, storeType, saleMonth, index);
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(saleMonth)) {
                LOGGER.error("downModelValidAreaEx.saleMonth:{}", saleMonth);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E001).getBytes());
                return;
            } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                LOGGER.error("downModelValidAreaEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E002).getBytes());
                return;
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelAnalyseInService.class.getName();
                String methodName = ExportConstants.ExportMethodName.EXPORT_MODEL_CONTRIBUTION_EX;

                String orgLevel = employeeInfo.getOrgLevel();
                String belongsDisCode = employeeInfo.getRegion5Code();
                String belongsBranchCode = employeeInfo.getBranchCode();

                @SuppressWarnings("unchecked")
                List<Object> params = new ArrayList<Object>(Arrays.asList(staffId, orgLevel, disCode, branchCode,
                        belongsDisCode, belongsBranchCode, storeType, saleMonth, index));
                exportFileUtil.saveExportTask(staffId, className, methodName, params);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (Exception e) {
            LOGGER.error("downModelValidAreaEx failed.", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        } finally {
            try {
                if (null != ouputStream) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("downModelValidAreaEx finally failed.", e);
            }
        }

        LOGGER.info("downModelContributionArea exit, disCode={}", disCode);
    }

    /**
     * 
     * 执行样机销售排行文件生成任务
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/createCommRankFileJob.do")
    public MyGsonView createCommRankFileJob() {
        LOGGER.info("createCommRankFileJob enter");
        ReturnMsg<String> ret = new ReturnMsg<String>();
        try {
            modelService.createCommRankFileJob();
        } catch (Exception e) {
            LOGGER.error("createCommRankFileJob error", e);
        }
        ret.setData("OK");
        return setGsonView(ret);
    }

    /**
     * 
     * 下载样机销售排行
     * 
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/downModelTop.do")
    public MyGsonView downModelTop() {
        LOGGER.info("downModelTop enter");
        ReturnMsg<String> ret = new ReturnMsg<String>();
        ret.setData(fsUrl + "uimg/snsawp/csv/modelSaleTopRank" + DateUtils.getLastMonth() + ".csv");
        LOGGER.info("downModelTop exit");
        return setGsonView(ret);
    }

    /**
     * 功能描述: pc后台查询商品的TOP<br>
     * 〈功能详细描述〉
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelTopTwenty/{orgLevel}.do")
    public MyGsonView queryModelTopTwenty(@PathVariable String orgLevel, String cateCode, String flag) {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        // 返回对象
        ReturnMsg<List<ModelRecommendBaseVo>> returnMsg = new ReturnMsg<List<ModelRecommendBaseVo>>();

        // 升降序标识位
        String tempFlag = flag;
        // 既不是降序，还不是升序，默认降序
        if (!ClerkConstants.TOP_DESC.equals(flag) && !ClerkConstants.TOP_ASC.equals(flag)) {
            tempFlag = ClerkConstants.TOP_DESC;
        }
        LOGGER.info("queryModelTopTwenty enter:" + employeeInfo.toString());
        LOGGER.info("p:cateCode" + cateCode + ",flag=" + flag + ",orgLevel=" + orgLevel);
        // 组织级别 0:分公司 1:大区
        if ("0".equals(orgLevel)) {
            // TODO 查看分公司top数据
            List<ModelRecommendBaseVo> result = modelService.queryModelTopTwenty(null, employeeInfo.getBranchCode(),
                    cateCode, tempFlag);
            returnMsg.setData(result);
        } else if ("1".equals(orgLevel)) {
            // TODO 查看大区top数据
            List<ModelRecommendBaseVo> result = modelService.queryModelTopTwenty(employeeInfo.getRegion5Code(), null,
                    cateCode, tempFlag);
            returnMsg.setData(result);
        }
        LOGGER.info("queryModelTopTwenty out:" + returnMsg.toString());
        return setGsonView(returnMsg);
    }

    /**
     * 功能描述: pc后台查询门店样机推荐<br>
     * 〈功能详细描述〉
     * 
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelRecommend/{orgLevel}.do")
    public MyGsonView queryModelRecommend(@PathVariable String orgLevel, String cateCode) {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        // 返回对象
        ReturnMsg<List<ModelRecommendBaseVo>> returnMsg = new ReturnMsg<List<ModelRecommendBaseVo>>();

        LOGGER.info("queryModelRecommend enter:" + employeeInfo.toString());
        LOGGER.info("p:cateCode" + cateCode + ",orgLevel=" + orgLevel);

        // 组织级别 0:分公司 1:大区
        if ("0".equals(orgLevel)) {
            // TODO 查看分公司推荐数据
            List<ModelRecommendBaseVo> result = modelService.queryRecommendCompany(employeeInfo.getBranchCode(),
                    cateCode);
            returnMsg.setData(result);
        } else if ("1".equals(orgLevel)) {
            // TODO 查看大区推荐数据
            List<ModelRecommendBaseVo> result = modelService.queryRecommendArea(employeeInfo.getRegion5Code(), cateCode);
            returnMsg.setData(result);
        }
        LOGGER.info("queryModelRecommend out:" + returnMsg.toString());
        return setGsonView(returnMsg);
    }
}
